package servlet;

import entity.User;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Auther:ws@itany.com
 * Date:20-9-16 上午11:46
 * Version:1.0
 * Description:
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String path = request.getServletPath();

        if ("/regist.user".equals(path)){
            regist(request,response);
        }

    }



    public void regist(HttpServletRequest request, HttpServletResponse response)throws ServletException{
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");

        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        UserService userService = (UserService) ac.getBean("userServiceImpl");
        User user = new User(username, password, phone, address);
        try {
            userService.regist(user);
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        } catch (Exception e) {
            request.setAttribute("registMsg",e.getMessage());
        }
    }
}
